﻿#region Header File
//
// Program.cs - Discrete channel with 256 input/output alphabet (byte channel) and with aditive 
//              white noise uniformly distributed.
//
// Copyright (C) Javier Valcarce. BSD License
#endregion


#region Using Statements
using System;
using System.Threading;
using System.IO;
using System.IO.Ports;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#endregion

class Program
{
    static double     byerr; // Byte Error Rate
    static string     ifile;
    static string     ofile;
    static BinaryReader br;
    static BinaryWriter bw;

    static Stream     istrm;
    static Stream     ostrm;
    static SerialPort icom;
    static SerialPort ocom;


    static void Main(string[] args)
    {
        ProcessArgs(args);

        Console.WriteLine("Byte channel {0} --> {1} with Byte Error Rate of {2:f4}", ifile, ofile, byerr);
        ByteChannel bc1 = new ByteChannel(byerr, istrm, ostrm);

        Console.WriteLine("Opening...");
        while (true)
        {
            Thread.Sleep(100);
            Console.Write("\rTX1->RX2 redirected {0} bytes with {1} errors", 
                bc1.ByteCount, bc1.ErrorCount);
        }
    }



    static void ProcessArgs(string[] args)
    {
        
        if (args.Length == 3)
        {
            // parameters
            ifile = args[0];
            ofile = args[1];
            byerr = Double.Parse(args[2]);
        }
        else
        {
            Console.WriteLine("ByteChannel.exe <ifile> <ofile> ByteErrorRate");
            Environment.Exit(1);
        }

        Console.WriteLine("Opening...");

        // INPUT
        if (File.Exists(ifile))
        {
            istrm = new FileStream(ifile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        }
        else
        {
            icom = new SerialPort(ifile, 9600);
            icom.Open();
            istrm = icom.BaseStream;
        }
        Console.WriteLine("Opening.ADFASDF..");
        // unified I/O
        if (ifile == ofile)
        {
            ostrm = istrm;
            return;
        }

        // OUTPUT
        if (File.Exists(ofile))
            ostrm = new FileStream(ofile, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);
        else
        {
            ocom = new SerialPort(ofile, 9600);
            ocom.Open();
            ostrm = ocom.BaseStream;
        }

    }
}

